package com.strato.logging.saas.v1_0_0;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.WeakHashMap;

import com.strato.base.cache.v1_0_0.TimedReference;
import com.strato.base.env.v1_0_0.GlobalEnvironment;

public class OutputManager{

	private Timer timer=new Timer();
	
	private OutputManager(){
		TimerTask task=new TimerTask() {
			@Override
			public void run() {
				clearHolder();
			}

		};
		timer.schedule(task, 6*1000);
	}
	
	private static OutputManager instance=null;
	
	private Map<String,TimedReference<Writer>> holder=new WeakHashMap<String,TimedReference<Writer>>();
	
	private void clearHolder() {
	}
	
	public static OutputManager getInstance(){
		if(instance!=null){
			return instance;
		}
		instance=new OutputManager();
		return instance;
	}
	
	public void output(String merchantId,String message,Throwable e){
		if(merchantId==null){
			return;
		}
		Writer writer=getWriter(merchantId);
		try {
			writer.write(message);
			if(e!=null){
				e.printStackTrace(new PrintWriter(writer));
			}
			writer.flush();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	private int cacheTTL=5*60*1000;
	
	private Writer getWriter(String merchantId) {
		String sDate=null;
		{
			Date date=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMdd");
			sDate=df.format(date);
		}
		String key=merchantId+"_"+sDate;
		TimedReference<Writer> ref = holder.get(key);
		if(ref!=null&&ref.getObject()!=null){
			ref.setCacheTime(System.currentTimeMillis());
			return ref.getObject();
		}
		String dirPath=GlobalEnvironment.getInstance().get("strato.log.saas.dir","d:/strato_mlogs");
		
		File dir=new File(dirPath+"/"+sDate);
		dir.mkdirs();
		File file=new File(dir,merchantId+".txt");
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(file));
			ref=new TimedReference<Writer>(writer,cacheTTL);
			holder.put(key, ref);
			return writer;
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}
